package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取request response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2. 通过request对象获取请求的地址
        String path = request.getURI().getPath();
        //3. 判断请求的地址是否是登录如果是则放行
        if(path.contains("/login_auth")){
            return chain.filter(exchange);
        }

        //4. 如果不是则获取请求头里面的token
        String token = request.getHeaders().getFirst("token");

        //5. 判断token是否为空如果为空则返回401
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //6. 如果不为空则校验token的合法性和有效性 如果校验通过则放行如果不通过则返回401
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);

            int result = AppJwtUtil.verifyToken(claimsBody);
            if(1 == result || 2== result){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //通过token获取登录用户的id
            String id = claimsBody.get("id").toString();

            //对request的请求头进行增强- 添加一个key-value键值对
            ServerHttpRequest serverHttpRequest = request.mutate().headers(new Consumer<HttpHeaders>() {
                @Override
                public void accept(HttpHeaders httpHeaders) {
                    httpHeaders.add("userId", id);
                }
            }).build();

            //替换老的request对象
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return chain.filter(exchange);
    }

    /**
     * 返回值是用来做过滤器的排序 值越小 优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
